package com.remoter.consumer.internal;

import java.lang.reflect.Method;

import com.remoter.basic.bean.support.ProviderModule;
import com.remoter.basic.bean.support.RemoterRequest;
import com.remoter.basic.bean.support.RemoterResponse;
import com.remoter.basic.consumer.support.AbstractInvoker;
import com.remoter.basic.transport.IClient;

/**
 * @author			koko
 * @date 			2017-08-09 11:26:22
 * @description 	类功能说明
 */
public class InternalInvoker extends AbstractInvoker{

	@Override
	protected Object doInvoke(ProviderModule providerModule, Object proxy, Method method, Object[] args)throws Throwable {
		String methodName = method.getName();
		Class<?>[] parameterTypes = method.getParameterTypes();
		if("toString".equals(methodName) && parameterTypes.length == 0){
			return this.toString();
		}
		if("hashCode".equals(methodName) && parameterTypes.length == 0){
			return this.hashCode();
		}
		if("equals".equals(methodName) && parameterTypes.length == 1){
			return this.equals(args[1]);
		}
		RemoterRequest remoterRequest = new RemoterRequest();
		remoterRequest.setProtocol(providerModule.getProtocol());
		remoterRequest.setType(providerModule.getType());
		remoterRequest.setMethod(methodName);
		remoterRequest.setBean(providerModule.getBean());
		remoterRequest.setParamObject(args);
		remoterRequest.setParamType(parameterTypes);
		
		this.consumerModule.setRemoteHost(providerModule.getHost());
		this.consumerModule.setRemotePort(providerModule.getPort());
		IClient client = this.consumer.getClient(this.consumerModule,true);
		if(null == client){
			throw new IllegalStateException("provider client not found");
		}
		logger.info("find client : " + providerModule.getKey());
		RemoterResponse remoterResponse = client.sendMessage(remoterRequest);
		if(remoterResponse.hasException()){
			throw new IllegalStateException(remoterResponse.getException());
		}
		return remoterResponse.getData();
	}
	
}